import { createStore } from 'vuex';
import getters from './getters';

// 自动导入modules目录下的模块
const modulesFiles = require.context('./modules', true, /\.js$/);
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1');
  const value = modulesFiles(modulePath);
  modules[moduleName] = value.default;
  return modules;
}, {});

export default createStore({
  state: {
    keepAliveList: ['layout', 'postMessage']
  },
  mutations: {
    addCacheRoute(state, name) {
      // 添加需要keep 的路由
      let idx = state.keepAliveList.findIndex(item => item === name);
      if (idx === -1) {
        state.keepAliveList.push(name);
      }
    },
    removeCacheRoute(state, name) {
      // 移除不需要keep 的路由
      let idx = state.keepAliveList.findIndex(item => item === name);
      if (idx >= 0) {
        state.keepAliveList.splice(idx, 1);
      }
    }
  },
  getters,
  modules
});
